package com.newhonor.springboot_shiro_redis.shiro.realms;

import com.newhonor.springboot_shiro_redis.entity.User;
import com.newhonor.springboot_shiro_redis.service.UserService;
import com.newhonor.springboot_shiro_redis.shiro.salt.MyByteSource;
import com.newhonor.springboot_shiro_redis.utils.ApplicationContextUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.ObjectUtils;

/**
 * 自定义realm
 *
 * @Author newhonor
 * @Date 2021/1/21 22:25
 * @Version 1.0
 **/
public class CustomerRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("=========Az=======");
        //获取身份信息
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        System.out.println("Az:调用："+primaryPrincipal);
        //根据主身份获取角色和权限信息
        if("xxr".equals(primaryPrincipal)){
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

//            simpleAuthorizationInfo.addRole("admin");
//            simpleAuthorizationInfo.addStringPermission("user:*:*");


            return simpleAuthorizationInfo;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("======Ac=========");

        String principal = (String) authenticationToken.getPrincipal();

        //在工厂中获取bean对象
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");

        User user = userService.findByUserName(principal);

        if(!ObjectUtils.isEmpty(user)){
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), new MyByteSource(user.getSalt()), this.getName());
        }

        return null;
    }
}
